package cn.zcscloud.mall.controller;

import cn.zcscloud.mall.common.CustomException;
import cn.zcscloud.mall.common.PageRequest;
import cn.zcscloud.mall.common.R;
import cn.zcscloud.mall.mbg.model.UmsAdmin;
import cn.zcscloud.mall.mbg.model.UmsRole;
import cn.zcscloud.mall.service.UmsAdminService;
import cn.zcscloud.mall.utils.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin")
@CrossOrigin //支持跨域访问
@Slf4j
public class UmsAdminController {

    @Autowired
    private UmsAdminService umsAdminService;

    /**
     * 根据用户名或姓名分页获取用户列表
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    public R<PageRequest> list(String keyword, Integer pageNum, Integer pageSize) {
        //分页构造器
        IPage<UmsAdmin> iPage = new Page<>(pageNum, pageSize);
        //查询构造器
        LambdaQueryWrapper<UmsAdmin> lqw = new LambdaQueryWrapper<>();
        lqw.like(keyword != null, UmsAdmin::getUsername, keyword).or().like(keyword != null, UmsAdmin::getNickName, keyword);
        lqw.orderByDesc(UmsAdmin::getCreateTime);
        //查询并构造返回值并返回
        umsAdminService.page(iPage, lqw);
        PageRequest pr = PageRequest.init(iPage);
        return R.success(pr);
    }

    /**
     * 获取指定用户的角色
     *
     * @param adminId
     * @return
     */
    @GetMapping("/role/{adminId}")
    public R<List<UmsRole>> role(@PathVariable("adminId") Integer adminId) {
        List<UmsRole> list = umsAdminService.role(adminId);
        return R.success(list);
    }

    /**
     * 给用户分配角色
     *
     * @param adminId
     * @param roleIds
     * @return
     */
    @PostMapping("/role/update")
    public R<String> updateRole(Integer adminId, @RequestParam List<Integer> roleIds) {
        log.info("adminid={}.,==================={}", adminId, roleIds);
        umsAdminService.updateRole(adminId, roleIds);
        return R.success(null);
    }

    /**
     * 修改指定用户信息
     *
     * @param umsAdmin
     * @return
     */
    @PostMapping("/update/{id}")
    public R<String> update(@RequestBody UmsAdmin umsAdmin) {
        String password = umsAdmin.getPassword();
        if (password.length() <= 20) {

            umsAdmin.setPassword(PasswordUtil.generate(password));
        }
        umsAdminService.updateById(umsAdmin);
        return R.success(null);
    }

    /**
     * 根据id删除指定用户信息
     *
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public R<String> deleteById(@PathVariable("id") Integer id) {
        umsAdminService.deleteById(id);
        return R.success(null);
    }

    /**
     * 用户注册
     *
     * @param umsAdmin
     * @return
     * @throws ParseException
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody UmsAdmin umsAdmin) throws ParseException {
        //判断用户名是否注册
        LambdaQueryWrapper<UmsAdmin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsAdmin::getUsername, umsAdmin.getUsername());
        UmsAdmin one = umsAdminService.getOne(lqw);
        if (one != null) {
            throw new CustomException("用户名已经注册了");
        }
        //密码加密
        umsAdmin.setPassword(PasswordUtil.generate(umsAdmin.getPassword()));
        //获取当前时间并设置上
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Date creatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nowTime);
        umsAdmin.setCreateTime(creatTime);
        //设置状态
        umsAdmin.setStatus(1);
        umsAdminService.save(umsAdmin);
        return R.success(null);
    }

    /**
     * 修改指定用户密码
     *
     * @param newPassword
     * @param oldPassword
     * @param username
     * @return
     */
    @PostMapping("/updatePassword")
    public R<String> updatePassword(String newPassword, String oldPassword, String username) {
        LambdaQueryWrapper<UmsAdmin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsAdmin::getUsername, username);
        UmsAdmin one = umsAdminService.getOne(lqw);
        if (one == null) {
            throw new CustomException("用户名不存在");
        }
        if (one.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
            throw new CustomException("新密码和旧密码相同");
        }
        one.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        umsAdminService.save(one);
        return R.success(null);
    }

    /**
     * 修改账号状态
     *
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/updateStatus/{id}")
    public R<String> updateStatus(@PathVariable("id") Integer id, Integer status) {
        UpdateWrapper<UmsAdmin> uw = new UpdateWrapper<>();
        uw.lambda().eq(UmsAdmin::getId, id);
        uw.lambda().set(UmsAdmin::getStatus, status);
        umsAdminService.update(uw);
        return R.success(null);
    }
}